package com.ruoyi.system.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.Student;
import com.ruoyi.system.dto.LoginOrRegisterParam;
import com.ruoyi.system.mapper.StudentMapper;
import com.ruoyi.system.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired private StudentMapper studentMapper;

    @Override
    public void register(LoginOrRegisterParam loginOrRegisterParam) {
        if (!StringUtils.equals(loginOrRegisterParam.getConfirmPassword(), loginOrRegisterParam.getPasswd())) {
            throw new RuntimeException("密码和确认密码不一致");
        }
        Student student = new Student();
        student.setStudentName(loginOrRegisterParam.getStudentName());
        student.setPasswd(loginOrRegisterParam.getPasswd());
        student.setGrade(loginOrRegisterParam.getGrade());
        student.setSignPhoto(loginOrRegisterParam.getSignPhoto());
        this.studentMapper.insert(student);
    }

    @Override
    public String login(LoginOrRegisterParam loginOrRegisterParam) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentName,loginOrRegisterParam.getStudentName())
                .eq(Student::getPasswd,loginOrRegisterParam.getPasswd());
        Student student = this.studentMapper.selectOne(wrapper);
        if (student == null) {
            throw new RuntimeException("账号信息用户名或密码错误");
        }
        StpUtil.login(student.getStudentId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo.tokenValue;
    }
}
